import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/ui/service_order/service_item_content_page.dart';

import '../../message/message_config.dart';
import '../../model/service_order/user_buton_role_mixin.dart';
import '../../net/post_request.dart';
import '../../net/response/response_data.dart';
import '../../net/response/service_item_content_list.dart';
import '../../net/response/service_item_list.dart';
import '../../net/response/service_order_list_data.dart';
import '../../ui/service_order/service_item_list_page.dart';

class SimpleServiceOrderListViewModel
    extends BaseListViewModel<ServiceOrderListData> with UserButonRoleMixin {
  final String statusId;

  SimpleServiceOrderListViewModel(BuildContext context, this.statusId)
      : super(context);

  var typeList = [
    PickerDataWithIdModel(pickName: "在住客户", pickId: "0"),
    PickerDataWithIdModel(pickName: "非在住客户", pickId: "1"),
  ];

  PickerDataWithIdModel? type;

  ServiceItemList? serviceItem;
  ServiceItemContentList? serviceContent;

  void chooseType() {
    DataPickerView(context, typeList, onSubmitListener: (p1, p2, p3) {
      type = typeList[p1];
      notifyListeners();
    }).show();
  }

  var canSend = false;

  var canReceive = false;

  var canStartOrder = false;

  var canFinishOrder = false;

  @override
  Future<List<ServiceOrderListData>> requestListData() async {
    var roleMap = await buttonRoleMap();
    canSend = roleMap['APP.MYJOB.SERVICEORDER.SEND'] ?? false;
    canReceive = roleMap['APP.MYJOB.SERVICEORDER.JOIN'] ?? false;
    canStartOrder = roleMap['APP.MYJOB.SERVICEORDER.BEGIN'] ?? false;
    canFinishOrder = roleMap['APP.MYJOB.SERVICEORDER.FINISH'] ?? false;

    var data = await PostRequest.serviceOrderListNoFilter(
        statusId, page, pageLength,
        type: type?.pickId,
        markStartDate: startDateStr,
        markEndDate: startDateStr,
        serveTypeId: serviceItem?.id,
        serveItemId: serviceContent?.id);
    var bean = ResponseData.fromJson(data,
        listBuilder: (i) => ServiceOrderListData.fromJson(i));
    if ("0" == bean.code) {
      return bean.data?.rows ?? [];
    } else {
      throw bean.msg ?? "";
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if (event.msgCode == MessageConfig.REFRESH_ORDER) {
      requestRefresh();
    }
  }

  Future<void> chooseServiceItem() async {
    var data = await Go().push(ServiceItemListPage());
    if (data != null) {
      serviceItem = data;
      notifyListeners();
      requestRefresh();
    }
  }

  Future<void> chooseServiceContent() async {
    var data = await Go()
        .push(ServiceItemContentPage(serviceItem?.id?.toString() ?? ""));
    if (data != null) {
      serviceContent = data;
      notifyListeners();
      requestRefresh();
    }
  }
}
